package com.drawu.drawuspring.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drawu.drawuspring.domain.DTO.ChatDto;
import com.drawu.drawuspring.domain.Result;
import com.drawu.drawuspring.domain.po.Chat;
import com.drawu.drawuspring.mapper.ChatMapper;
import com.drawu.drawuspring.service.IChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drawu.drawuspring.utils.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

import static com.drawu.drawuspring.utils.Coze.runWorkflow1;
import static com.drawu.drawuspring.utils.Coze.runWorkflowStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hui
 * @since 2025-03-27
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {

    @Override
    public ResponseBodyEmitter chat(ChatDto chatDto) throws Exception {
//        Integer userId = AppThreadLocalUtil.getUser().getId();
//        JSONObject jsonObject = runWorkflow1(chatDto.getQuestion(),"7486059684798218251");
//        String answer = jsonObject.getString("output");
//        Chat chat = new Chat();
//        chat.setAnswer(answer);
//        chat.setQuestion(chatDto.getQuestion());
//        chat.setUserId(userId.longValue());
//        this.save(chat);
//        log.info(answer);L
        String question =  chatDto.getQuestion();
        return runWorkflowStream("7486059684798218251", question);
    }

    @Override
    public Result listHistory() {
        Integer userId = AppThreadLocalUtil.getUser().getId();
        return Result.success(this.lambdaQuery().eq(Chat::getUserId, userId.longValue()).orderByDesc(Chat::getCreateTime).list());
    }

    @Override
    public Result deleteHistory() {
        Integer userId = AppThreadLocalUtil.getUser().getId();
        QueryWrapper<Chat> wrapper = new QueryWrapper<Chat>().eq("user_id", userId.longValue());
        return remove(wrapper) ? Result.success() : Result.fail("删除失败");
//        return remove(this.lambdaQuery().eq(Chat::getUserId, userId.longValue())) ? Result.success() : Result.fail("删除失败");
    }
}
